//能力维护

import {Button, Col, Input, Row, Select, Table, Tag} from 'antd';
import React, {PureComponent} from "react";
import {connect} from "umi";
import {Drawer} from "antd/es";
import Form from "antd/es/form";
import TextArea from "antd/es/input/TextArea";
import {guid, getIndicatorById, listByIndicator} from "@/pages/RadarChart/base/DataLoad";
import PlusOutlined from "@ant-design/icons/lib/icons/PlusOutlined";
import SelectSearch from "@/pages/RadarChart/base/SelectSearch";
import NumInput from "@/pages/RadarChart/base/NumInput";
import MinusCircleOutlined from "@ant-design/icons/lib/icons/MinusCircleOutlined";


class AbilityEdit extends PureComponent {

  state = {
    drawerVisible: false,
    drawerData: {}
  }
  formRef = React.createRef();

  columns = [
    {
      title: '名称',
      dataIndex: 'name',
      key: "name",
    },
    {
      title: '指标权重',
      dataIndex: 'rule',
      render: (data) => {
        if (data == null) {
          return "";
        }

        let str = "";
        let sumWeight = 0;
        for (let i in data) {

          let name = getIndicatorById(i).name;
          let weight = data[i];
          sumWeight += weight;
          str += "+" + name + "*" + weight;
        }
        if (str != "") {
          str = str.substr(1, str.length);
          str = "(" + str + ")/" + sumWeight;
        }
        return str;
      },
      key: 'weight'
    }, {
      title: '操作',
      key: '操作',
      render: (text, record) => {


        return <div>
          <Button onClick={() => this.edit(record)}>编辑</Button>
          <Button onClick={() => this.delete(record.abilityId)}>删除</Button>
        </div>
      }

    }
  ];

  edit(data) {
    this.openDrawer(data);
  }

  delete(id) {
    const dispatch = this.props.dispatch;
    return dispatch({
      type: 'radarCharModel/deleteAbility',
      payload: {id: id},
    }).then(() => {
      this.list();
    });
  }

  list = () => {
    const dispatch = this.props.dispatch;

    dispatch({
      type: 'radarCharModel/listIndicator',
      payload: {},
    });
    return dispatch({
      type: 'radarCharModel/listAbility',
      payload: {},
    });
  }

  componentDidMount() {
    this.list();
  }

  renderForm(data) {
    if (this.formRef.current) {
      this.state.drawerData = data;
      this.formRef.current.resetFields();
      this.formRef.current.setFieldsValue(data);
    } else {
      setTimeout(() => {
        this.renderForm(data)
      }, 100);
    }
  }

  openDrawer(data) {

    let map = data.rule;
    let array = [];
    for (let i in map) {
      let object = {...getIndicatorById(i)};
      object.weight = map[i];
      array.push(object);
    }
    data.ruleArray = array;
    this.state.drawerData = JSON.parse(JSON.stringify(data));
    this.renderForm(data);

    this.setState({drawerVisible: true});
  }

  onClose() {
    this.setState({drawerVisible: false})
  }

  onFinish(data) {
    console.log(data);
    const dispatch = this.props.dispatch;
    dispatch({
      type: 'radarCharModel/saveAbility',
      payload: data,
    }).then(() => {
      this.list();
    });
  }

  refreshDrawer() {

    let data = JSON.parse(JSON.stringify(this.state.drawerData));

    this.setState({drawerData: data});

  }

  render() {
    let drawerData = this.state.drawerData;
    let exclude = [];
    for (let i in drawerData.rule) {
      exclude.push(i);
    }

    return <div>
      <Drawer
        title={this.state.drawerData.indicatorId ? "编辑能力" : "新增能力"}
        placement="right"
        closable={false}
        width={"60%"}
        onClose={() => {
          this.onClose()
        }}
        visible={this.state.drawerVisible}
        footer={
          <div
            style={{
              textAlign: 'right',
            }}
          >
            <Button onClick={() => {
              this.onClose()
            }} style={{marginRight: 8}}>
              Cancel
            </Button>
            <Button onClick={() => {
              this.onClose();
              this.formRef.current.submit();
            }} type="primary">
              Submit
            </Button>
          </div>
        }

      >
        <Form ref={this.formRef} name="control-hooks" onFinish={(data) => {
          let ruleArray = this.state.drawerData.ruleArray;
          data.rule = {}
          delete data['ruleArray'];
          for (let item of ruleArray) {
            data.rule[item.indicatorId] = item.weight;
          }

          this.onFinish(data);
        }}>
          <Form.Item name="abilityId">
            <Input type={"hidden"}/>
          </Form.Item>
          <Form.Item name="name" rules={[{required: true}]} label={"指标名称"}>
            <Input type={"text"}/>
          </Form.Item>


          <div>
            {drawerData.ruleArray ? drawerData.ruleArray.map((item, index) => {

              return <Row gutter={16} key={"r" + index}>
                <Col span={13}>
                  <Form.Item
                    label={"指标"}
                    required={true}

                  >
                    {/*fixme select 做成从后台查数据*/}
                    <SelectSearch mark={item} onChange={(value, mark) => {
                      item.indicatorId = value;
                    }} load={(value, call) => {
                      let array = listByIndicator(value);

                      call(array);
                    }}
                                  data={item.name ? [{name: item.name, value: item.id}] : []}
                                  defaultValue={item.id}
                                  key={guid()}
                    ></SelectSearch>

                  </Form.Item>
                </Col>
                <Col span={8}>
                  <Form.Item
                    label={"权重"}
                    required={true}

                  >
                    <NumInput min={0} max={100} onChange={(value) => {
                      item.weight = value;

                    }} defaultValue={item.weight}></NumInput>
                  </Form.Item>
                </Col>
                <Col span={3}>
                  <MinusCircleOutlined
                    className="dynamic-delete-button"
                    style={{margin: '0 8px'}}
                    onClick={() => {
                      drawerData.ruleArray.splice(index, 1);

                      this.refreshDrawer();
                    }}
                  />
                </Col>
              </Row>
            }) : ""}
          </div>
          <Form.Item>
            <Button
              type="dashed"
              onClick={() => {
                drawerData.ruleArray.push({});
                this.refreshDrawer();
              }}
              style={{width: '60%'}}
            >
              <PlusOutlined/> 添加指标
            </Button>
          </Form.Item>


        </Form>

      </Drawer>
      <Button onClick={() => this.openDrawer({})}>新增能力</Button>
      <Table dataSource={this.props.radarCharModel.ability} columns={this.columns}></Table>
    </div>
      ;
  }
}

export default connect(({radarCharModel, loading}) => ({
  radarCharModel: radarCharModel,
}))(AbilityEdit);
